<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>layui</title>
    <meta name="renderer" content="webkit" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
    <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all" />
    <link rel="stylesheet" href="../../css/public.css" media="all" />
    <style>
      body {
        background-color: #ffffff;
      }
    </style>
  </head>
  <body>
    <div class="layui-form layuimini-form">
      <div class="layui-form-item">
        <label class="layui-form-label required">角色名称</label>
        <div class="layui-input-block">
          <input
            type="text"
            name="roleName"
            lay-verify="required"
            lay-reqtext="角色名称不能为空"
            placeholder="请输入用角色名称"
            value=""
            class="layui-input" />
          <tip>填写菜单名称。</tip>
          <input type="hidden" name="roleId" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">角色编码</label>
        <div class="layui-input-block">
          <input
            type="text"
            name="roleKey"
            lay-verify="required"
            lay-reqtext="角色编码不能为空"
            placeholder="请输入用角色编码"
            value=""
            class="layui-input"
            disabled />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">显示顺序</label>
        <div class="layui-input-block">
          <input type="number" name="orderNum" placeholder="请输入顺序" value="" class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">角色状态</label>
        <div class="layui-input-block">
          <input type="radio" name="status" value="0" title="正常" checked="" />
          <input type="radio" name="status" value="1" title="停用" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">角色描述</label>
        <div class="layui-input-block">
          <input type="text" name="remark" value="" class="layui-input" />
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label required">权限范围</label>
        <div class="layui-input-block">
          <select name="dataScope" lay-verify="required" lay-filter="demo-select-filter">
            <option value="">直接选择或搜索选择</option>
            <option value="1">全部数据权限</option>
            <option value="2">自定数据权限</option>
            <option value="3" selected>本部门数据权限</option>
            <option value="4">本部门及以下数据权限</option>
            <option value="5">仅本人数据权限</option>
          </select>
        </div>
      </div>

      <div class="layui-form-item" id="shezhi" style="display: none">
        <label class="layui-form-label required">数据权限</label>
        <div class="layui-input-block">
          <div style="height: 350px; overflow: auto">
            <ul id="deptTree" class="dtree" data-id="0" lay-verify="deptData"></ul>
          </div>
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label required">菜单权限</label>
        <div class="layui-input-block">
          <div style="height: 350px; overflow: auto">
            <ul id="menuTree" class="dtree" data-id="0"></ul>
          </div>
        </div>
      </div>
      <div class="layui-form-item">
        <div class="layui-input-block">
          <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
      </div>
    </div>
    <script th:src="@{/lib/layui-v2.6.3/layui.js}" charset="utf-8"></script>
    <script th:src="@{/js/lay-config.js?v=2.0.0}" charset="utf-8"></script>

    <script th:inline="none">
      layui.use(['form', 'layer', 'tableSelect', 'dtree'], function () {
        var form = layui.form,
          dtree = layui.dtree,
          layer = layui.layer,
          tableSelect = layui.tableSelect,
          $ = layui.jquery

        var dataPerms = []
        var menuIds = []

        window.init = function (formObj) {
          $("[name='roleId']").val(formObj.roleId)
          $("[name='roleName']").val(formObj.roleName)
          $("[name='roleKey']").val(formObj.roleKey)
          $("[name='orderNum']").val(formObj.orderNum)
          $("[name='remark']").val(formObj.remark)
          $(`[name='status'][value=${formObj.status}]`).attr('checked', true)
          form.render('radio')
          $("[name='dataScope']").val(formObj.dataScope)
          form.render('select')
          if (formObj.dataScope == 2) {
            $('#shezhi').show()
          } else {
            $('#shezhi').hide()
          }

          $.ajax({
            url: '/sys-role/query/' + formObj.roleId,
            type: 'get',
            async: false,
            success: function (result) {
              if (result.success) {
                let data = result.data
                if (data.dataPermissions) {
                  dataPerms = data.dataPermissions
                }
                if (data.menuIds) {
                  menuIds = data.menuIds
                }
              }
            }
          })
        }

        form.on('select(demo-select-filter)', function (data) {
          var elem = data.elem // 获得 select 原始 DOM 对象
          var value = data.value // 获得被选中的值
          var othis = data.othis // 获得 select 元素被替换后的 jQuery 对象
          if (value == 2) {
            $('#shezhi').show()
          } else {
            $('#shezhi').hide()
          }
        })

        form.verify({
          deptData: function (value, item) {
            let dataScope = $("[name='dataScope']").val()
            if (dataScope == 2) {
              let checkbarNodes = dtree.getCheckbarNodesParam('deptTree')
              if (!checkbarNodes || checkbarNodes.length == 0) {
                return '数据权限不能为空'
              }
            }
          },
          menuData: function (value, item) {
            let checkbarNodes = dtree.getCheckbarNodesParam('menuTree')
            if (!checkbarNodes || checkbarNodes.length == 0) {
              return '菜单权限不能为空'
            }
          }
        })

        //监听提交
        form.on('submit(saveBtn)', function (data) {
          console.log(JSON.stringify(data.field))

          let reqData = { ...data.field }
          reqData.dataPermissions = []
          reqData.menuIds = []
          if (reqData.dataScope == 2) {
            let dataPerms = dtree.getCheckbarNodesParam('deptTree')
            for (let elem of dataPerms.values()) {
              reqData.dataPermissions.push(elem.nodeId)
            }
          }
          let menuPerms = dtree.getCheckbarNodesParam('menuTree')
          for (let elem of menuPerms.values()) {
            reqData.menuIds.push(elem.nodeId)
          }
          if (1 == 1) {
            $.ajax({
              url: '/sys-role/update',
              type: 'post',
              async: false,
              data: JSON.stringify(reqData),
              contentType: 'application/json',
              success: function (result) {
                if (result.success) {
                  layer.msg(result.msg, { icon: 1, time: 1000 }, function () {
                    parent.layer.close(parent.layer.getFrameIndex(window.name))
                    parent.reload()
                  })
                } else {
                  layer.msg(result.msg, { icon: 2, time: 1000 })
                }
              }
            })
          }
          return false
        })

        var deptTree = dtree.render({
          elem: '#deptTree',
          initLevel: '2', //默认展开层级为1
          line: true, // 有线树
          ficon: ['1', '-1'], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
          icon: ['0', '2'], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
          record: true, // 开启数据记录模式
          method: 'post',
          url: '/sys-dept/query',
          dataStyle: 'layuiStyle',
          dataFormat: 'list',
          response: {
            message: 'msg',
            statusCode: 0,
            treeId: 'deptId', //节点ID（必填）
            parentId: 'parentId', //父节点ID（必填）
            title: 'deptName' //节点名称（必填）},
          },
          width: '100%',
          checkbar: true,
          checkbarType: 'self',
          success: function (data, obj, first) {
            let treeData = data.data
            for (let elem of treeData.values()) {
              elem.checkArr = '0'
            }
          },
          done: function (data, obj, first) {
            // 异步加载完毕后回调，参数：1是本次加载的数据，2是组件的根节点的jQuery对象，3是表示是否第一次加载，可以打开控制台看看是什么参数哦
            if (first && dataPerms.length > 0) {
              //初始化选中
              //dtree.chooseDataInit("deptTree", "001001,001002");
              // 反选半选状态
              //dtree.initNoAllCheck("deptTree");
              dtree.chooseDataInit('deptTree', dataPerms)
            }
          }
        })
        // 绑定节点的双击
        dtree.on("node('deptTree')", function (obj) {
          // if (!obj.param.leaf) {
          //   var $div = obj.dom;
          //   deptTree.clickSpread($div); //调用内置函数展开节点
          // }
          var nodeId = obj.param.nodeId
          deptTree.clickNodeCheckbar(nodeId) // 点击节点选中复选框
        })
        //菜单权限
        var menuTree = dtree.render({
          elem: '#menuTree',
          initLevel: '2', //默认展开层级为1
          line: true, // 有线树
          ficon: ['1', '-1'], // 设定一级图标样式。0表示方形加减图标，8表示小圆点图标
          icon: ['0', '2'], // 设定二级图标样式。0表示文件夹图标，5表示叶子图标
          record: true, // 开启数据记录模式
          method: 'post',
          url: '/sys-menu/query',
          dataStyle: 'layuiStyle',
          dataFormat: 'list',
          response: {
            message: 'msg',
            statusCode: 0,
            treeId: 'menuId', //节点ID（必填）
            parentId: 'parentId', //父节点ID（必填）
            title: 'menuName' //节点名称（必填）},
          },
          width: '100%',
          checkbar: true,
          checkbarType: 'all',
          success: function (data, obj, first) {
            let treeData = data.data
            for (let elem of treeData.values()) {
              elem.checkArr = '0'
            }
          },
          done: function (data, obj, first) {
            // 异步加载完毕后回调，参数：1是本次加载的数据，2是组件的根节点的jQuery对象，3是表示是否第一次加载，可以打开控制台看看是什么参数哦
            if (first && menuIds.length > 0) {
              dtree.chooseDataInit('menuTree', menuIds)
            }
          }
        })
        // 绑定节点的双击
        dtree.on("node('menuTree')", function (obj) {
          var nodeId = obj.param.nodeId
          menuTree.clickNodeCheckbar(nodeId) // 点击节点选中复选框
        })
      })
    </script>
  </body>
</html>
